<template>
  <div class="role-lists">
    <el-button class="addRole" @click="addRole()" type="primary"
      >添加角色</el-button
    >
    <el-table
      :stripe="true"
      :border="true"
      :data="roleLists"
      style="width: 100%"
    >
      <!-- 表格展开 -->
      <!-- 直接展开div，在div里面做更简单。。。 -->
      <el-table-column type="expand">
        <template v-slot="{ row }">
          <div class="innerBox">
            <el-row
              class="authBox"
              v-for="ele in row.children"
              :key="ele.id"
              type="flex"
              align="middle"
            >
              <el-col style="height: 100%; margin: auto 0" :span="5">
                <el-tag @close="deleteQuanxian(row, ele)" closable>
                  {{ ele.authName }}</el-tag
                ><span class="el-icon-caret-right"></span
              ></el-col>
              <el-col :span="19">
                <el-row
                  type="flex"
                  align="middle"
                  class="authChi"
                  v-for="ele in ele.children"
                  :key="ele.id"
                >
                  <el-col class="authChi" :span="8">
                    <el-tag
                      @close="deleteQuanxian(row, ele)"
                      type="success"
                      closable
                      >{{ ele.authName }}</el-tag
                    ><span class="el-icon-caret-right"></span>
                  </el-col>
                  <el-col :span="14">
                    <el-tag
                      @close="deleteQuanxian(row, chi)"
                      type="warning"
                      v-for="chi in ele.children"
                      :key="chi.id"
                      closable
                      >{{ chi.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="编号" type="index" width="50">
      </el-table-column>
      <el-table-column label="角色名称" prop="roleName"> </el-table-column>
      <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            size="small"
            icon="el-icon-edit"
            type="primary"
            @click="editRole(row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            icon="el-icon-delete"
            type="danger"
            @click="deleteBtn(row)"
            >删除</el-button
          >
          <el-button
            size="small"
            icon="el-icon-setting"
            type="warning"
            @click="addQuanxian(row)"
            >分配角色</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 弹出框在这里 -->
    <div class="tankuang">
      <!-- 添加角色弹框 -->
      <!-- 添加角色与编辑角色使用一个弹框 -->
      <el-dialog width="45%" title="添加角色" :visible.sync="dialogFormVisible">
        <el-form
          :model="addARole"
          :rules="rulesRole"
          ref="ruleForm"
          class="demo-ruleForm"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input
              v-model="addARole.roleName"
              placeholder="请输入角色名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input
              v-model="addARole.roleDesc"
              placeholder="请输入角色描述"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="okBtn()">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 分配角色弹框 -->
      <el-dialog
        v-if="quanxianLists.length && isnot"
        title="分配角色"
        :visible.sync="dialogFormVisible2"
      >
        <el-tree
          ref="quanxian"
          :data="quanxianLists"
          show-checkbox
          node-key="id"
          default-expand-all
          :default-checked-keys="idArr"
          :props="defaultProps"
        >
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="editQuanxian()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleLists: [
        {
          roleDesc: "",
          roleName: "",
          children: [
            {
              authName: "",
            },
          ],
        },
      ],
      quanxianLists: [],
      defaultProps: {
        children: "children",
        label: "authName",
      },
      idArr: [],
      isnot: false,
      quanxianChi: null,
      //角色信息存储
      addARole: {
        roleName: "",
        roleDesc: "",
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
      rulesRole: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "change" },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "change" },
          // { min: 3, message: "长度不得小于3个字符", trigger: "change" },
        ],
      },
      //弹框状态判断
      isAdd: true,
    };
  },
  created() {
    this.getRoles();
    this.getQuanXian();
  },
  watch: {
    dialogFormVisible(newValue) {
      if (!newValue) {
        this.addARole = {
          roleName: "",
          roleDesc: "",
        };
        this.$refs.ruleForm.resetFields();
        // console.log(this.addARole);
      }
    },
    dialogFormVisible2(newValue) {
      if (!newValue) {
        this.isnot = false;
      } else {
        this.isnot = true;
      }
    },
  },
  methods: {
    async getRoles() {
      // const res = await this.$axios.get("rights/tree");
      const res = await this.$axios.get("roles");
      // console.log(res);
      this.roleLists = res.data.data;
      // console.log(this.roleLists);
    },

    //获取树形权限列表
    async getQuanXian() {
      const res = await this.$axios.get("rights/tree");
      this.quanxianLists = res.data.data;
      // console.log(this.quanxianLists);
    },

    //打开添加角色弹框
    addRole() {
      this.dialogFormVisible = true;
      this.isAdd = true;
    },
    //打开编辑角色弹框
    editRole(row) {
      this.dialogFormVisible = true;
      this.isAdd = false;
      this.addARole = { ...row };
    },
    //弹出框提交按钮
    okBtn() {
      this.$refs.ruleForm.validate(async (valid) => {
        // let res = null;
        if (valid) {
          // console.log("ok");
          if (this.isAdd) {
            const res = await this.$axios.post("roles", this.addARole);
            if (res.data.meta.status === 201) {
              this.$message({
                message: "创建成功",
                type: "success",
              });
              this.roleLists.push({ ...this.addARole });
              this.dialogFormVisible = false;
            } else {
              this.$message({
                message: res.data.meta.msg,
                type: "warning",
              });
            }
          } else if (!this.isAdd) {
            const res = await this.$axios.put(
              `roles/${this.addARole.id}`,
              this.addARole
            );
            if (res.data.meta.status === 200) {
              this.dialogFormVisible = false;
              // const editIndex = this.roleLists.findIndex(
              //   (ele) => ele.id === this.addARole.id
              // );
              // this.roleLists[editIndex] = {
              //   ...this.roleLists[editIndex],
              //   ...this.addARole,
              // };
              this.getRoles();
              this.$message({
                message: "编辑成功",
                type: "success",
              });
            }
          }
        }
      });
    },
    //删除角色按钮
    deleteBtn(row) {
      const roleIndex = this.roleLists.findIndex((ele) => ele.id === row.id);
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$axios.delete(`roles/${row.id}`);
          if (res.data.meta.status === 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.roleLists.splice(roleIndex, 1);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //分配角色按钮
    addQuanxian(row) {
      this.idArr = [];
      this.quanxianChi = row;
      this.dialogFormVisible2 = true;
      this.getIdArray(row.children);
    },
    //获取扁平化id数组
    getIdArray(arr) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].children) {
          this.getIdArray(arr[i].children);
        } else {
          this.idArr.push(arr[i].id);
        }
      }
    },
    async editQuanxian() {
      // getCheckedKeys
      const quanxianArr1 = this.$refs.quanxian.getCheckedKeys().join();
      const quanxianArr2 = this.$refs.quanxian.getHalfCheckedKeys().join();
      const quanxianArr = quanxianArr1 + "," + quanxianArr2;
      // console.log(this.quanxianChi);
      await this.$axios.post(`roles/${this.quanxianChi.id}/rights`, {
        rids: quanxianArr,
      });
      this.getRoles();
      this.$message({
        message: "分配角色成功",
        type: "success",
      });
      this.dialogFormVisible2 = false;
    },

    //删除单项权限
    deleteQuanxian(row, ele) {
      // console.log(row, ele);
      this.$confirm("此操作将删除该项权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await this.$axios.delete(
            `roles/${row.id}/rights/${ele.id}`
          );
          console.log(res);
          // this.getRoles();
          const index = this.roleLists.findIndex((ele) => ele.id === row.id);
          this.roleLists[index].children = res.data.data;
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style  lang='less'>
.role-lists {
  padding: 15px;
  .addRole {
    margin-bottom: 15px;
  }
}
.innerBox {
  .authBox:last-child {
    border-bottom: 1px solid #ebeef5;
  }
  .authBox {
    border-top: 1px solid #ebeef5;
    .el-tag {
      margin-top: 5px;
      margin-bottom: 5px;
      margin-right: 10px;
    }
    .authChi {
      border-top: 1px solid #ebeef5;
    }
    .el-col div:nth-child(1) {
      border-top: none;
    }
  }
}
</style>